package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.common.BaseServiceImpl;
import com.usian.common.constants.user.WemediaContans;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmNewsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.spring.web.json.Json;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class WmNewsServiceImpl extends BaseServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    @Value("${fdfs.url}")
    private String fileServerUrl;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper materialMapper;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {

        if (dto == null) return errorResult;
        Integer userId = WmThreadLocalUtils.getUserId();
        if (userId == null) return errorResult;
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNews::getUserId, userId);
        if (dto.getStatus() != null) wrapper.eq(WmNews::getStatus, dto.getStatus());
        if (dto.getChannelId() != null) wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        if (dto.getKeyword() != null) wrapper.like(WmNews::getTitle, dto.getKeyword());
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null)
            wrapper.between(WmNews::getCreatedTime, dto.getBeginPubDate(), dto.getEndPubDate());
        Page<WmNews> page = new Page<>(dto.page, dto.size);
        IPage<WmNews> iPage = page(page, wrapper);
        ResponseResult result = new PageResponseResult(dto.page, dto.size, (int) iPage.getTotal());
        result.setData(iPage.getRecords());
        result.setHost(fileServerUrl);
        return result;
    }

    @Override
    public ResponseResult saveNews(WmNewsDto wmNews, Short isSubmit) {
        if (wmNews == null || wmNews.getContent().isEmpty()) return errorResult;
        WmNews news = new WmNews();
        //将前端传过来的内容赋值到要保存的表里的对象
        BeanUtils.copyProperties(wmNews, news);
        if (WemediaContans.WM_NEWS_TYPE_AUTO.equals(wmNews.getType())) {
            wmNews.setType(null);
        }
        if (wmNews.getImages() != null && wmNews.getImages().size() != 0) {
            StringBuffer buffer = new StringBuffer();
            wmNews.getImages().forEach(s -> buffer.append(s).append(","));
            news.setImages(buffer.toString().substring(0, buffer.toString().length() - 1));
            ;
        }
        news.setStatus(isSubmit);
        news.setUserId(WmThreadLocalUtils.getUserId());
        news.setCreatedTime(new Date());
        news.setSubmitedTime(new Date());
        news.setEnable((short) 1);
        //对象字段赋值完后，还有两件事 1.确定素材和新闻关系 2.保存新闻
        if (news.getId() == null) {//以前没有这个文章，新增文章
            save(news);
        } else {//有id说明是修改文章
            //删除关系表中新闻和素材的关系数据
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, news.getId()));
            //更新修改内容
            updateById(news);
        }
        //将前端传过来的新闻内容中的资源提取出来保存到集合中
        String content = wmNews.getContent();
        List<String> materials = new ArrayList<>();
        JSONArray array = JSON.parseArray(content);
        array.forEach(m -> {
            JSONObject object = JSON.parseObject(m.toString());
            if (object.get("type").equals(WemediaContans.WM_NEWS_TYPE_IMAGE)) {
                materials.add(object.get("value").toString().replace(fileServerUrl, ""));
            }
        });
        if (isSubmit == WmNews.Status.SUBMIT.getCode()) {
            if (materials.size() != 0) {//保存新闻内容中素材和新闻的关系
                ResponseResult responseResult = saveRelativeInfoForContent(materials, news.getId());
                if (responseResult != null) {
                    return responseResult;
                }
            }
            //保存封面资源和新闻的关系数据
            ResponseResult responseResult = saveRelativeInfoForCover(wmNews, materials, news);
            if (responseResult != null) {
                return responseResult;
            }
        }
        return null;
    }
    /**
     * 保存封面资源和新闻的关系数据
     *
     * @param wmNews       前端传过来的新闻对象
     * @param materialList 包含所有详情内容资源路劲的集合
     * @param news         要更新或保存到表里的新闻对象
     * @return
     */
    private ResponseResult saveRelativeInfoForCover(WmNewsDto wmNews, List<String> materialList, WmNews news) {
        //前端传过来的封面图集合
        List<String> images = wmNews.getImages();
        //如果前端再提交数据时，封面选择的是自动
        if (wmNews.getType() == WemediaContans.WM_NEWS_TYPE_AUTO) {
            if (materialList.size() == 0) {//无图模式
                news.setType(WemediaContans.WM_NEWS_NONE_IMAGE);
            } else if (materialList.size() <= 2) {//单图模式
                news.setType(WemediaContans.WM_NEWS_SINGLE_IMAGE);
                if (images == null) images = new ArrayList<>();
                images.clear();
                images.add(materialList.get(0));
            } else {//多图模式
                news.setType(WemediaContans.WM_NEWS_MANY_IMAGE);
                images = materialList.stream().limit(3).collect(Collectors.toList());
            }
            //更新已保存的新闻表中封面图的数据
            if (images.size() != 0)
                news.setImages(images.toString().replace("[", "")
                        .replace("]", "").replace(fileServerUrl, "")
                        .replace(" ", ""));
            updateById(news);
        }
        if (images != null && images.size() > 0) {
            images = images.stream().map(i->i.replace(fileServerUrl,"")).collect(Collectors.toList());
            ResponseResult responseResult = saveRelativeInfo(images, news.getId(),WemediaContans.WM_COVER_REFERENCE);
            if (responseResult != null) {
                return responseResult;
            }
        }
        return sucResult;
    }

    /**
     * 保存新闻内容中素材和新闻的关系
     *
     * @param materialList
     * @param id
     * @return
     */
    private ResponseResult saveRelativeInfoForContent(List<String> materialList, Integer id) {
        return saveRelativeInfo(materialList, id, WemediaContans.WM_CONTENT_REFERENCE);
    }

    /**
     * 具体执行中间关系表的数据插入
     *
     * @param materialList       内容中引用的资源路劲集合
     * @param id                 新闻id
     * @param wmContentReference 引用类型，当前是内容引用
     * @return
     */
    private ResponseResult saveRelativeInfo(List<String> materialList, Integer id, Short wmContentReference) {
       //通过图片路径的集合查到图片对象的集合
        List<WmMaterial> list = materialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materialList));
        if (list == null || list.size() == 0) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "资源错误");
        List<String> idList = new ArrayList<>();
        list.forEach(l -> idList.add(l.getId().toString()));
        wmNewsMaterialMapper.saveRelationsByContent(idList, id, wmContentReference);
        return null;
    }

    //根据文章id查询
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1.参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        //2.查询数据
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        //3.结果返回
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }
    //删除
    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        //3.判断当前文章的状态  status==9  enable == 1
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable().equals(WemediaContans.WM_NEWS_ENABLE_UP)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }

        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));

        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        //3.判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }

        //4.修改文章状态，同步到app端（后期做）TODO
        if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
